﻿namespace SupportSystemUI.Controls.Utility.Other
{
    using System;
    using System.ComponentModel;
    using System.IO;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Media.Imaging;

    /// <summary>
    /// Interaction logic for ImageLoader.xaml
    /// </summary>
    public partial class ImageLoader : UserControl
    {
        /// <summary>
        /// Governs images saving and loading.
        /// </summary>
        private static int magicIndex = 0;

        /// <summary>
        /// Initializes a new instance of the <see cref="ImageLoader"/> class.
        /// </summary>
        public ImageLoader()
        {
            this.InitializeComponent();

            this.Loaded += (sender, args) =>
            {
                DoubleAnimation animation = new DoubleAnimation
                {
                    From = 0,
                    To = 360,
                    Duration = new Duration(TimeSpan.FromSeconds(1.5)),
                    RepeatBehavior = RepeatBehavior.Forever,
                };

                RotateTransform rotation = new RotateTransform
                {
                    CenterX = this.loopIcon.ActualWidth / 2,
                    CenterY = this.loopIcon.ActualHeight / 2,
                };

                rotation.BeginAnimation(RotateTransform.AngleProperty, animation);
                this.loopIcon.RenderTransform = rotation;
            };
        }

        /// <summary>
        /// Sets the image contained in this control.
        /// </summary>
        /// <param name="url">Url to fetch the image from.</param>
        public void SetImage(string url)
        {
            BackgroundWorker worker = new BackgroundWorker();
            string fileName = Path.GetTempPath() + "img_" + (ImageLoader.magicIndex++) + Path.GetExtension(url);

            worker.DoWork += (sender, args) =>
            {
                WebClient webClient = new WebClient();
                webClient.DownloadFile(url, fileName);
            };

            worker.RunWorkerCompleted += (sender, args) =>
            {
                this.imageHolder.Source = new BitmapImage(new Uri(fileName, UriKind.Absolute));
                this.imageHolder.SourceUpdated += (sender2, args2) => File.Delete(fileName);
                this.loopIcon.Visibility = Visibility.Hidden;
            };

            worker.RunWorkerAsync();
        }
    }
}
